<?php

namespace Chengjingvet\QywxHandel;

class QywxHandel
{
    public $corpid, $corpsecret, $agentId;

    public function __construct($corpid,$corpsecret,$agentId)
    {
        $this->corpid = $corpid?$corpid:Config::$corpid;
        $this->corpsecret = $corpsecret?$corpsecret:Config::$corpsecret;
        $this->agentId = $agentId?$agentId:Config::$agentId;
    }

    /**
     * 获取accesstoken
     * @return string
     */
    public function getAccessToken(): string
    {
        if (!$this->hasConfig()) {
            trigger_error("config is not complete!", E_USER_ERROR);
        }
        $fileName = $this->agentId . 'qytoken.php';

        $data = json_decode(Tools::getPHPFile($fileName));

        if ($data->expire_time < time()) {
            $urlObj['corpid'] = $this->corpid;
            $urlObj['corpsecret'] = $this->corpsecret;
            $bizString = Tools::toUrlParams($urlObj);
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?' . $bizString;
            $res = Tools::getData($url);
            $res = json_decode($res, true);
            $token = !$res['access_token'] ? '' : $res['access_token'];
            if ($token) {
                $data->expire_time = time() + 5000;
                $data->access_token = $token;
                Tools::setPHPFile($fileName, json_encode($data));
            }
        } else {
            $token = $data->access_token;
        }
        return $token;
    }

    /**
     * 获取部门信息
     * @return  string|array
     */
    public function getDepartMents()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . $this->getAccessToken();
        $res = Tools::getData($url);
        $arr = json_decode($res, true);
//        print_r($arr);
        if ($arr['errcode'] == 0) {
            return $arr['department'];
        } else {
            return $arr['errmsg'];
        }
    }

    /**
     * 获取指定部门下的部门成员
     * @param $dpid int 部门id
     * @return string|array
     */
    public function getDepartUsers(int $dpid)
    {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=' . $dpid . '&access_token=' . $this->getAccessToken();
        $res = Tools::getData($url);
        $arr = json_decode($res, true);
        if ($arr['errcode'] == 0) {
            return $arr['userlist'];
        } else {
            return $arr['errmsg'];
        }
    }

    /**
     * 发送文字消息
     * @param $userIds string   要发送的用户id 多个用户用"|"分割
     * @param $msgContent string    要发送的消息内容
     * @return array
     */
    public function sendFontMsg(string $userIds, string $msgContent): array
    {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $this->getAccessToken();
        $data = [
            "touser" => $userIds,
            "msgtype" => 'text',
            "agentid" => $this->agentId,
            "text" => [
                "content" => $msgContent
            ]
        ];
        $res = Tools::getData($url, json_encode($data));
        $result = json_decode($res, true);
        if ($result['errcode'] == 0) {
            return ["errcode" => $result['errcode'], "msg" => '发送成功'];
        } else {
            return ["errcode" => $result['errcode'], "msg" => $result['errmsg']];
        }
    }

    /**
     * 发送卡片消息
     * @param string $userIds 要发送的用户id 多个用户用"|"分割
     * @param string $title 卡片标题
     * @param string $msgContent 卡片消息内容
     * @param string $moreUrl 更多的链接地址
     * @return array
     */
    public function sendCardMsg(string $userIds, string $title, string $msgContent, string $moreUrl = "javascript:;")
    {
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $this->getAccessToken();
        $data = [
            "touser" => $userIds,
            "msgtype" => 'textcard',
            "agentid" => $this->agentId,
            "textcard" => [
                "title" => $title,
                "description" => $msgContent,
                "url" => $moreUrl,
                "btntxt" => "更多"
            ]
        ];
        $res = Tools::getData($url, json_encode($data));
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            return ["errcode" => $res['errcode'], "msg" => '发送成功'];
        } else {
            return ["errcode" => $res['errcode'], "msg" => $res['errmsg']];
        }
    }
    /**
     * 上传临时素材
     * 图片（image）：10MB，支持JPG,PNG格式
     * 语音（voice） ：2MB，播放长度不超过60s，仅支持AMR格式
     * 视频（video） ：10MB，支持MP4格式
     * 普通文件（file）：20MB
     * @param $data
     * @param $type
     * @return string
     */
    public function updateFile($data,$type):string{
        $url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" . $this->getAccessToken() . "&type=" . $type;
        $res = Tools::getData($url, json_encode($data));
        $result = json_decode($res, 1);
        return $result["errcode"] == 0 ? $result["media_id"] : "";
    }

    /**
     * 判断参数是否完整
     * @return bool
     */
    private function hasConfig(): bool
    {
        $hasComplete = true;
        if ($this->corpid == "" || empty($this->corpid)) $hasComplete = false;
        if ($this->corpsecret == "" || empty($this->corpsecret)) $hasComplete = false;
        if ($this->agentId == "" || empty($this->agentId)) $hasComplete = false;
        return $hasComplete;
    }
}
